/**
 * 
 */
package dt.inlee.system.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.util.SystemResourceUtil;
import dt.inlee.common.vo.PageBean;
import dt.inlee.domain.SysMenu;
import dt.inlee.domain.SysRole;
import dt.inlee.domain.SysUser;
import dt.inlee.system.service.SysRoleService;
import dt.inlee.system.service.SysUserService;
import dt.inlee.system.vo.DictionaryBean;
import dt.inlee.system.vo.SysMenuBean;
import dt.inlee.system.vo.SysRoleBean;
import dt.inlee.system.vo.SysUserLoginBean;

/**
 * @功能说明：系统角色控制层
 * @作者： 印鲜刚
 * @创建日期： 2010-5-9 @
 */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("sysRoleAction")
public class SysRoleAction extends ActionSupport {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserService sysUserService;

	private PageBean pageBean = new PageBean();
	private SysRoleBean sysRoleBean = new SysRoleBean();
	private List<SysRoleBean> sysRoleBeans = new ArrayList<SysRoleBean>();
	private List<SysMenuBean> sysMenuBeans = new ArrayList<SysMenuBean>();
	private List<DictionaryBean> sysRoleSBeans = new ArrayList<DictionaryBean>();
	private boolean result;
	private JSONObject jsonObject;

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public SysRoleBean getSysRoleBean() {
		return sysRoleBean;
	}

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public List<DictionaryBean> getSysRoleSBeans() {
		return sysRoleSBeans;
	}

	public void setSysRoleSBeans(List<DictionaryBean> sysRoleSBeans) {
		this.sysRoleSBeans = sysRoleSBeans;
	}

	@Validations(visitorFields = { @VisitorFieldValidator(message = "test", fieldName = "model", appendPrefix = false) })
	public void setSysRoleBean(SysRoleBean sysRoleBean) {
		this.sysRoleBean = sysRoleBean;
	}

	public List<SysRoleBean> getSysRoleBeans() {
		return sysRoleBeans;
	}

	public void setSysRoleBeans(List<SysRoleBean> sysRoleBeans) {
		this.sysRoleBeans = sysRoleBeans;
	}

	public List<SysMenuBean> getSysMenuBeans() {
		return sysMenuBeans;
	}

	public void setSysMenuBeans(List<SysMenuBean> sysMenuBeans) {
		this.sysMenuBeans = sysMenuBeans;
	}

	public boolean isResult() {
		return result;
	}

	public void setResult(boolean result) {
		this.result = result;
	}

	/**
	 * 进入角色添加页面
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "createSysRole", results = @Result(name = "success", location = "/page/system/sys_role_detail.jsp"))
	@SkipValidation()
	public String createSysRole() throws FrameworkException {
		this.sysRoleSBeans = SystemResourceUtil.getInstance()
				.getResourceAsList("sysRoleS");
		return SUCCESS;
	}

	/**
	 * 添加角色
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "saveSysRole", results = {
			@Result(name = "success", location = "/page/system/sys_role_list.jsp"),
			@Result(name = "input", location = "/page/system/sys_role_detail.jsp") })
	public String saveSysRole() throws FrameworkException {

		SysUserLoginBean sysUserLoginBean = (SysUserLoginBean) ActionContext
				.getContext().getSession().get(CommonConstant.SESSION_USER);
		SysUser loginUser = null;
		try {
			loginUser = this.sysUserService.findSysUserById(sysUserLoginBean
					.getId());
		} catch (FrameworkException e) {
			e.printStackTrace();
		}
		int wyId = loginUser.getWyId();
		if (!BaseUtil.isEmpty(this.sysRoleService.findSysRoleByName(
				this.sysRoleBean.getName(), wyId))) {
			this.addFieldError("name", "已有该角色名称!");
			return INPUT;
		}

		SysRole sysRole = new SysRole();
		BeanUtils.copyProperties(this.sysRoleBean, sysRole);
		sysRole.setFlag("1");
		sysRole.setWyId(wyId);
		this.sysRoleService.saveSysRole(sysRole);
		return SUCCESS;
	}

	/**
	 * 修改角色
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "modifySysRole", results = {
			@Result(name = "success", location = "/page/system/sys_role_list.jsp"),
			@Result(name = "input", location = "/page/system/sys_role_modify.jsp") })
	public String modifySysRole() throws FrameworkException {
		// if
		// (!BaseUtil.isEmpty(this.sysRoleService.findSysRoleByIdAndName(this.sysRoleBean.getId(),
		// this.sysRoleBean
		// .getName()))) {
		// this.addFieldError("name", "已有该角色名称!");
		// return INPUT;
		// }
		// SysRole sysRole =
		// this.sysRoleService.findSysRoleById(this.sysRoleBean.getId());
		// BeanUtils.copyProperties(this.sysRoleBean, sysRole);
		// this.sysRoleService.modifySysRole(sysRole);
		return SUCCESS;
	}

	/**
	 * 通过角色ID获取获取角色信息
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "findSysRole", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String findSysRole() throws FrameworkException {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		this.sysRoleSBeans = SystemResourceUtil.getInstance()
				.getResourceAsList("sysRoleS");
		if (!BaseUtil.isEmpty(this.sysRoleBean.getId())) {
			SysRole sysRole = this.sysRoleService
					.findSysRoleById(this.sysRoleBean.getId());
			BeanUtils.copyProperties(sysRole, this.sysRoleBean);
		}
		jsonMap.put("sysRoleBean", this.sysRoleBean);
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}

	/**
	 * 通过角色ID删除角色信息
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "deleteSysRole", results = { @Result(name = "success", type = "chain", location = "findAllSysRoles") })
	@SkipValidation()
	public String deleteSysRole() throws FrameworkException {
		this.sysRoleService.deleteSysRoleById(this.sysRoleBean.getId());
		return SUCCESS;
	}

	/**
	 * 通过多个角色ID，系统删除多角色信息
	 */
	@Action(value = "deleteSysRoles", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String deleteSysRoles() throws FrameworkException {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			this.sysRoleService.deleteSysRoles(this.sysRoleBean.getDeleteIDs()
					.split(","));
			jsonMap.put("flag", true);
		} catch (Exception e) {
			jsonMap.put("flag", false);
			e.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}

	/**
	 * 查询角色
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "findAllSysRoles", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String findAllSysRoles() throws FrameworkException, Exception {
		SysUserLoginBean sysUserLoginBean = (SysUserLoginBean) ActionContext
				.getContext().getSession().get(CommonConstant.SESSION_USER);
		SysUser loginUser = null;
		try {
			loginUser = this.sysUserService.findSysUserById(sysUserLoginBean
					.getId());
		} catch (FrameworkException e) {
			e.printStackTrace();
		}
		int wyId = loginUser.getWyId();
		List<SysRole> roleList = loginUser.getSysRoles();// 登录人员角色组
		// jqGrid查询转码-utf-8
		BaseUtil.decodeObject(this.sysRoleBean);
		this.pageBean.init(this.sysRoleService
				.getSysRoleTotalRows(this.sysRoleBean.getName()));
		List<SysRole> sysRoles = this.sysRoleService.findAllSysRoles(
				this.sysRoleBean.getName(), this.pageBean.getCurPage(),
				this.pageBean.getPageSize(), wyId, roleList);
		for (SysRole sysRole : sysRoles) {
			SysRoleBean bean = new SysRoleBean();
			BeanUtils.copyProperties(sysRole, bean);
			bean.setSysRoleS(BaseUtil.isEmpty(bean.getSysRoleS())
					|| bean.getSysRoleS().equals("-1") ? "未指定"
					: SystemResourceUtil.getInstance()
							.getCnNameOfBusinessDictionary("sysRoleS",
									bean.getSysRoleS()));
			this.sysRoleBeans.add(bean);
		}
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", sysRoleBeans);
		jsonMap.put("total", sysRoles.size());
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}

	/**
	 * 根据角色ID设置系统菜单
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "setSysMenu", results = { @Result(type = "json", params = {
			"excludeNullProperties", "true", "includeProperties", "result" }) })
	@SkipValidation()
	public String setSysMenu() throws FrameworkException {
		this.sysRoleService.setSysMenu(this.sysRoleBean.getId(), BaseUtil
				.isEmpty(this.sysRoleBean.getSysMenuIDs()) ? null
				: this.sysRoleBean.getSysMenuIDs().split(","));
		this.result = true;
		return SUCCESS;
	}

	/**
	 * 通过角色ID获取角色及其关联菜单信息
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "findSysMenusBySysRoleId", results = { @Result(type = "json", params = {
			"excludeNullProperties", "true", "excludeProperties",
			"sysRoleBean,sysRoleBeans" }) })
	@SkipValidation()
	public String findSysMenusBySysRoleId() throws FrameworkException {
		SysRole sysRole = this.sysRoleService.findSysRoleById(this.sysRoleBean
				.getId());
		BeanUtils.copyProperties(sysRole, this.sysRoleBean);
		List<SysMenu> sysMenus = sysRole.getSysMenus();
		for (SysMenu sysMenu : sysMenus) {
			SysMenuBean sysMenuBean = new SysMenuBean();
			BeanUtils.copyProperties(sysMenu, sysMenuBean);
			this.sysMenuBeans.add(sysMenuBean);
		}
		return SUCCESS;
	}

	/**
	 * 添加角色
	 * 
	 * @return
	 * @throws FrameworkException
	 * @throws IllegalAccessException
	 * @throws UnsupportedEncodingException
	 * @throws IllegalArgumentException
	 */
	@Action(value = "saveSysTemRole", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	public String saveSysTemRole() throws FrameworkException,
			IllegalArgumentException, UnsupportedEncodingException,
			IllegalAccessException {
		BaseUtil.decodeObject(sysRoleBean);
		SysUserLoginBean sysUserLoginBean = (SysUserLoginBean) ActionContext
				.getContext().getSession().get(CommonConstant.SESSION_USER);
		SysUser loginUser = this.sysUserService
				.findSysUserById(sysUserLoginBean.getId());
		// 企业id
		int wyId = loginUser.getWyId();
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		SysRole sysRole = null;
		if (!BaseUtil.isEmpty(this.sysRoleBean.getId())) {
			if (BaseUtil
					.isEmpty(this.sysRoleService.findSysRoleByIdAndName(
							this.sysRoleBean.getId(),
							this.sysRoleBean.getName(), wyId))) {
				sysRole = this.sysRoleService.findSysRoleById(this.sysRoleBean
						.getId());
				sysRole.setRemark(this.sysRoleBean.getRemark());
				sysRole.setName(this.sysRoleBean.getName());
				sysRole.setCode(this.sysRoleBean.getCode());
				this.sysRoleService.modifySysRole(sysRole);
				jsonMap.put("flag", true);
			} else {
				jsonMap.put("flag", false);
				jsonMap.put("content", "已有该角色名称!");
			}
		} else {
			// 查询该企业下是否重名
			if (!BaseUtil.isEmpty(this.sysRoleService.findSysRoleByName(
					this.sysRoleBean.getName(), wyId))) {
				jsonMap.put("flag", false);
				jsonMap.put("content", "已有该角色名称!");
			} else {
				sysRole = new SysRole();
				BeanUtils.copyProperties(this.sysRoleBean, sysRole);
				sysRole.setFlag("1");
				sysRole.setWyId(wyId);
				this.sysRoleService.saveSysRole(sysRole);
				jsonMap.put("flag", true);
			}
		}
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
}
